<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('pageNetwork.modal.editHostnameTitle')"
    width="500"
  >
    <el-form ref="hostNameFormRef" :model="form" :rules="rules">
      <el-form-item :label="$t('pageNetwork.hostname')" prop="hostname">
        <el-input v-model="form.hostname" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetForm()">
          {{ $t('global.action.cancel') }}
        </el-button>
        <el-button type="primary" @click="onOk">
          {{ $t('global.action.add') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import useVuelidateTool from '@/hooks/useVuelidateTool';
const { useVuelidate, required, pattern, elementInputValidator } =
  useVuelidateTool();

const dialogVisible = ref(false);
const form = reactive({ hostname: '' });
const hostNameFormRef = ref();
const emit = defineEmits(['ok']);
const props = defineProps<{ hostname: string }>();

watch(
  () => props.hostname,
  () => {
    form.hostname = props.hostname;
  },
);

// Set vuelidate rules.
const v$ = useVuelidate(
  {
    hostname: { required, pattern: pattern.value(/^\S{0,64}$/) },
  },
  form,
);

// validators
const rules = computed(() => {
  return {
    hostname: [
      {
        trigger: 'change',
        validator: elementInputValidator.value(v$, 'hostname'),
      },
    ],
  };
});

const closeModal = () => {
  nextTick(() => {
    dialogVisible.value = false;
  });
};

const resetForm = () => {
  form.hostname = props.hostname;
  hostNameFormRef.value.clearValidate();
  closeModal();
};

const onOk = async () => {
  v$.value.$touch();
  if (v$.value.$invalid) return;
  closeModal();
  emit('ok', { HostName: form.hostname });
};

defineExpose({
  dialogVisible,
});
</script>

<style lang="scss" scoped></style>
